import { Component, OnInit } from '@angular/core';
import {ResponseUtil} from '../../../util/response-util';
import {Path} from '../../../portal/admin/admin-breadcrumb/breadcrumb';
import {PageSubject} from '../../../util/page-subject';
import {TableUtil} from '../../../util/table-util';
import {DaPmoriginService} from './da-pmorigin.service';
import {DaAPI} from '../da-constants';
import {MsgConstants} from '../../../constants/constants';
import {OneDialogService} from '../../../widgets/one-dialog/one-dialog.service';

declare var $;
declare var moment;

@Component({
  selector: 'app-da-pmorigin',
  templateUrl: './da-pmorigin.component.html',
  styleUrls: ['./da-pmorigin.component.css']
})
export class DaPmoriginComponent implements OnInit {

  // 数据格式
  timeDataType = 'hourData';
  timeDataArr: Array<any> = [];
  // 日期选择
  startDate = new Date(moment().subtract(1, 'w').format('YYYY/MM/DD HH:00'));
  endDate =  new Date();
 // 站点
  siteCode = '';
  rangeCode = '';
  // 多选
  factorDataArr: Array<any> = [];

  table: any;
  tableData: Array<any> = [];

  siteArr: Array<any> = [];

  /**
   * 禁用日期数组
   * @type {any[]}
   */
  disabledDate: Array<any> = [];

  constructor(
    private pageSubject: PageSubject,
    private tableUtil: TableUtil,
    private dialogService: OneDialogService,
    private responseUtil: ResponseUtil,
    private pmoriginService: DaPmoriginService
  ) { }

  ngOnInit() {
    this.pushPage();
    this.initData();
    this.getSiteData();
  }
  /**
   * 面包屑导航
   */
  pushPage() {
    // const path = new Path('多因子分析', '');
    this.pageSubject.pushPage('原始数据', '查询');
  }

  /**
   * 初始化数据
   */
  initData() {
    this.timeDataArr = [{name: '小时', dataType: 'hourData'}, { name: '日', dataType: 'dayData'}, {name: '周', dataType: 'weekData'}];
    this.factorDataArr = [
      {
        dataType: '重金属仪器数据',
        factor: [
          {label: 'PM2.5', value: 'PM2_5', name: 'PM<sub>2.5</sub>'},
          {label: '钾', value: 'k', name: 'K'},
          {label: '氯', value: 'cl', name: 'Cl'},
          {label: '氩', value: 'ar', name: 'Ar'},
          {label: '钙', value: 'ca', name: 'Ca'},
          {label: '钪', value: 'sc', name: 'Sc'},
          {label: '钛', value: 'ti', name: 'Ti'},
          {label: '钒', value: 'v', name: 'V'},
          {label: '铬', value: 'cr', name: 'Cr'},
          {label: '锰', value: 'mn', name: 'Mn'},
          {label: '铁', value: 'fe', name: 'Fe'},
          {label: '钴', value: 'co', name: 'Co'},
          {label: '镍', value: 'ni', name: 'Ni'},
          {label: '铜', value: 'cu', name: 'Cu'},
          {label: '锌', value: 'zn', name: 'Zn'},
          {label: '镓', value: 'ga', name: 'Ga'},
          {label: '砷', value: 'as', name: 'As'},
          {label: '硒', value: 'se', name: 'Se'},
          {label: '溴', value: 'br', name: 'Br'},
          {label: '锶', value: 'sr', name: 'Sr'},
          {label: '钼', value: 'mo', name: 'Mo'},
          {label: '钯', value: 'pd', name: 'Pd'},
          {label: '银', value: 'ag', name: 'Ag'},
          {label: '镉', value: 'cd', name: 'Cd'},
          {label: '锡', value: 'sn', name: 'Sn'},
          {label: '锑', value: 'sb', name: 'Sb'},
          {label: '碲', value: 'te', name: 'Te'},
          {label: '铯', value: 'cs', name: 'Cs'},
          {label: '钡', value: 'ba', name: 'Ba'},
          {label: '汞', value: 'hg', name: 'Hg'},
          {label: '铊', value: 'tl', name: 'Tl'},
          {label: '铅', value: 'pb', name: 'Pb'},
          {label: '硅', value: 'si', name: 'Si'},
          {label: '硫', value: 's', name: 'S'},
          {label: '磷', value: 'p', name: 'P'},
          {label: '铝', value: 'al', name: 'Al'}
        ]
      },
      {
        dataType: '离子色谱数据',
        factor: [
          { label: '氯离子', value: 'Cl', name: 'Cl⁻'},
          { label: '硝酸根离子', value: 'NO3', name: 'NO₃⁻'},
          { label: '硫酸根离子', value: 'SO4', name: 'SO₄²⁻'},
          { label: '钠离子', value: 'Na', name: 'Na⁺'},
          { label: '铵根离子', value: 'NH4', name: 'NH₄⁺'},
          { label: '钾离子', value: 'K', name: 'K⁺'},
          { label: '镁离子', value: 'Mg', name: 'Mg²⁺'},
          { label: '钙离子', value: 'Ca', name: 'Ca²⁺'},
          { label: '二氧化硫', value: 'SO2', name: 'SO₂'},
          { label: '氯化氢', value: 'HCl', name: 'HCl'},
          { label: '亚硝酸', value: 'HNO2', name: 'HNO₂'},
          { label: '硝酸', value: 'HNO3', name: 'HNO₃'},
          { label: '氨气', value: 'NH3', name: 'NH₃'}
        ]
      },
      {
        dataType: '气溶胶有机碳分析仪',
        factor: [
          { label: '有机碳', value: 'ocugCSTPm', name: 'OC'},
          { label: '元素碳', value: 'ecugCSTPm', name: 'EC'}
        ]
      }
    ];
    this.tableData = [];
  }
  /**
   * 时间类型切换
   * @param timeDataType
   */
  timeDataChange(timeDataType) {
    if (this.timeDataType === timeDataType) {
      return false;
    }
    this.timeDataType = timeDataType;
    this.changeStartAndEndDate();
    this.search();
  }

  /**
   * 日期选择
   */
  startValueChange = () => {
    // if (this.startDate > this.endDate) {
    //   this.startDate = null;
    //   this.dialogService.info('开始时间大于结束时间')
    // }
  };
  endValueChange = () => {
    // if (this.startDate > this.endDate) {
    //   this.endDate = null;
    //   this.dialogService.info('结束时间小于开始时间')
    // }
  };
  disabledStartDate = (startValue) => {
    if (!startValue || !this.endDate) {
      return false;
    }
    if (this.disabledDate.length > 0) {
      const isInRangeArr: Array<boolean> = [];
      let isInRange = false;
      this.disabledDate.forEach((val) => {
        const startTime = new Date(moment(val.startDate).format('YYYY/MM/DD 00:00:00'));
        const endTime = new Date(moment(val.endDate).format('YYYY/MM/DD 23:59:59'));
        isInRangeArr.push(startTime.getTime() <= startValue.getTime()  &&  startValue.getTime() <= endTime.getTime())
      });
      if (isInRangeArr.indexOf(true) !== -1) {
        isInRange = true;
      }
      return startValue.getTime() > Date.now() || startValue.getTime() > this.endDate.getTime() || !isInRange;
    } else {
      return startValue.getTime() > Date.now() || startValue.getTime() > this.endDate.getTime();
    }
  };
  disabledEndDate = (endValue) => {
    if (!endValue || !this.startDate) {
      return false;
    }
    const startDateTime =  new Date(moment(this.startDate).format('YYYY/MM/DD')).getTime();
    if (this.disabledDate.length > 0) {
      const isInRangeArr: Array<boolean> = [];
      let isInRange = false;
      this.disabledDate.forEach((val) => {
        const startTime = new Date(moment(val.startDate).format('YYYY/MM/DD 00:00:00'));
        const endTime = new Date(moment(val.endDate).format('YYYY/MM/DD 23:59:59'));
        isInRangeArr.push(startTime.getTime() <= endValue.getTime()  && endValue.getTime() <= endTime.getTime())
      });
      if (isInRangeArr.indexOf(true) !== -1) {
        isInRange = true;
      }
      return endValue.getTime() > Date.now() || endValue.getTime() < startDateTime || !isInRange;
    } else {
      return endValue.getTime() > Date.now() || endValue.getTime() < startDateTime;
    }
  };
  get showTimeParams() {
    if (this.timeDataType === 'hourData') {
      return {
        nzFormat: 'HH'
      }
    } else {
      return false;
    }
  }
  /**
   * aa
   * @returns {any[]}
   */
  addColumns = () => {
    // const data = {};
    const colArr = [[], []];
    // const colArr = [];
    // colArr[0].push({
    //   field: 'monitorTime',
    //   title: '时间',
    //   valign: 'middle',
    //   halign: 'center',
    //   rowspan: 2
    // });
    const indexArr = [];
    let type = '';
    this.factorDataArr.forEach((val, i) => {
      if (val.type !== type) {
        type = val.type;
        indexArr.push({col: i, name: type === 'ITP_HM' ? '重金属仪器数据' : type === 'ITP_IC' ? '离子色谱数据' : '气溶胶有机碳分析仪'});
      }
      if (val.flag) {
        colArr[1].push({field: val.code, title: val.name, align: 'right'});
        // colArr.push({field: val.code, title: val.name, align: 'right'});
      } else {
        colArr[0].push({field: val.code, title: val.name, valign: 'middle', align: 'center', rowspan: 2});
      }
    });
    if (indexArr.length > 0) {
      const factorLength = this.factorDataArr.length;
      const indexLength = indexArr.length - 1;
      indexArr.forEach((val, i) => {
        const col = i !== indexLength ?  indexArr[i + 1].col - val.col : factorLength - val.col;
        colArr[0].push({field: '', title: val.name, valign: 'middle', align: 'left', colspan: col});
      })
    }
    // this.factorDataArr.forEach((val) => {
    //   colArr[0].push({
    //     field: '',
    //     title: val.dataType,
    //     valign: 'middle',
    //     halign: 'left',
    //     colspan: val.factor.length
    //   });
    //   val.factor.forEach((factor) => {
    //     colArr[1].push({
    //       field: factor.value,
    //       title: factor.name,
    //       valign: 'middle',
    //       halign: 'right'
    //     });
    //     const value = factor.value;
    //     data[value] = factor.name;
    //   })
    // });
    return colArr
  };
  loadPMOri() {
    this.table = this.tableUtil.load('one_table_pmorigin',  {
      columns: this.addColumns(),
      idField: 'id',
      sidePagination: 'server',
      pagination: true,
      pageNumber: 1,
      pageSize: 15,
      pageList: [10, 15, 50],
      paginationPreText: '上一页',
      paginationNextText: '下一页',
      singleSelect: false, // 多选
      clickToSelect: true, // 点击选中
      toolbar: '#one_operation_pmorigin',
      url: DaAPI.pmOriginal,
      method: 'get',
      // 传递附加参数
      queryParams: (params) => {
        params.siteCode = this.siteCode;
        params.dataType = this.timeDataType;
        params.tableDataType =  'tableData';
        // params.pageNum = params.offset ? (params.offset / params.limit) + 1 : 1;
        // params.pageCount = params.limit;
        params.startTime = this.startDate ? moment(this.startDate).format('YYYY-MM-DD HH:00:00') : '';
        params.endTime = this.endDate ? moment(this.endDate).format('YYYY-MM-DD HH:00:00') : '';
        return params;
      },
      // 返回数据处理器
      responseHandler: (result) => {
        return this.responseUtil.bsPageHandler(result, () => {
        });
      },
      height: 700, // table高度
      sortable: true,
      order: 'asc',
      classes: 'table table-hover',
      striped: true, // 隔行变色
      paginationLoop: false, // 是否开启循环分页
      mobileResponsive: true // 响应式
    });
  }

  /**
   * 查询
   */
  search() {
    if (this.startDate > this.endDate) {
      this.dialogService.info('开始时间大于结束时间，请重新选择');
    } else {
      this.tableUtil.refreshOptions({pageNumber: 1});
    }
  }

  /**
   * 格式化数据
   * @param value
   * @param row
   * @param index
   * @returns {string}
   */
  formatColor = (value, row, index) => {
    return '<div style="padding: 8px;background: ' + this.aqiColor(value) + ';"> ' + value + '</div>'
  };
  /**
   * 等级颜色
   * @param data
   * @returns {string}
   */
  aqiColor = (data) => {
    const num = parseFloat(data);
    if (!num) {
      return 'rgb(52,54,199)';
    }
    if (num === 1.00) {
      return 'rgba(240,72,100,0.85)';
    } else if (num > 0.50) {
      return 'rgba(250,204,20,0.85)';
    } else if (num > 0.00) {
      return 'rgba(47,194,91,0.85)';
    } else if (num > -0.50) {
      return 'rgba(24,144,255,0.85)';
    } else {
      return 'rgba(52,54,199,0.85)';
    }
  };
  /**
   * 获取站点数据
   */
  getSiteData = () => {
    this.pmoriginService.getSiteData().subscribe(
      result => this.responseUtil.success(result, this.progressD),
      error => this.responseUtil.error(error)
    )
  };
  progressD = (result) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      if (result.data && result.data.length > 0) {
        this.siteArr = result.data;
        this.siteCode = this.siteArr[0].SITECODE;
        this.rangeCode = this.siteArr[0].RANGECODE;
        this.changeSite(false);
      }
    } else {
      this.dialogService.info(result.message);
    }
    this.getTableHeadData();
  };
  changeSite = (isOpen) => {
    if (!isOpen) {
      if (this.rangeCode) {
        this.disabledDate = [];
        let site;
        this.siteArr.every((val) => {
          if (val.RANGECODE === this.rangeCode) {
            this.siteCode = val.SITECODE;
            site = val;
            return false
          } else {
            return true
          }
        });
        if (site.DATESTR && typeof site.DATESTR === 'string' ) {
          const dateArr = site.DATESTR.split(';');
          if (dateArr.length > 0) {
            dateArr.forEach((val) => {
              const singleDateArr = val.split(',');
              this.disabledDate.push({startDate: singleDateArr[0], endDate: singleDateArr[1]})
            });
            this.changeStartAndEndDate();
          }
        }
      } else {
        this.disabledDate = [];
      }
    }
  };
  /**
   * 修改开始结束时间
   */
  changeStartAndEndDate = () => {
    if (this.disabledDate.length > 0) {
      const dateLength = this.disabledDate.length;
      const dateObj = this.disabledDate[dateLength - 1];
      const startTime = new Date(moment(dateObj.startDate).format('YYYY/MM/DD 00:00:00'));
      const endTime = new Date(moment(dateObj.endDate).format('YYYY/MM/DD 00:00:00'));
      const nowDate =  new Date(moment().format('YYYY/MM/DD 00:00:00'));
      const nowDateIsInRange = startTime.getTime() < nowDate.getTime()  && nowDate.getTime() <= endTime.getTime();
      if (nowDateIsInRange) {
        this.endDate = new Date(moment().format('YYYY/MM/DD HH:00'));
        let startDate = new Date(moment(dateObj.startDate).format('YYYY/MM/DD HH:00'));
        if (this.timeDataType === 'hourData') {
          startDate = new Date(moment().subtract('1', 'd').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'dayData') {
          startDate = new Date(moment().subtract('1', 'w').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'weekData') {
          startDate = new Date(moment().subtract('1', 'M').format('YYYY/MM/DD HH:00'));
        }
        const startDateIsInRange = startTime.getTime() < startDate.getTime()  && startDate.getTime() < endTime.getTime();
        if (startDateIsInRange) {
          this.startDate = startDate;
        } else {
          this.startDate = new Date(moment(dateObj.startDate).format('YYYY/MM/DD HH:00'));
        }
      } else {
        this.startDate = new Date(moment(dateObj.startDate).format('YYYY/MM/DD HH:00'));
        let endDate = new Date(moment(dateObj.endDate).format('YYYY/MM/DD HH:00'));
        if (this.timeDataType === 'hourData') {
          endDate = new Date(moment(dateObj.startDate).add('1', 'd').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'dayData') {
          endDate = new Date(moment(dateObj.startDate).add('1', 'w').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'weekData') {
          endDate = new Date(moment(dateObj.startDate).add('1', 'M').format('YYYY/MM/DD HH:00'));
        }
        if (endDate.getTime() > new Date().getTime()) {
          this.endDate = new Date(moment().format('YYYY/MM/DD HH:00'));
        } else {
          this.endDate = endDate;
        }
      }
    }
  };
  /**
   * 获取表格数据
   */
  getTableHeadData = () => {
    const dataObj = {
      siteCode: this.siteCode,
      dataType: this.timeDataType,
      tableDataType: 'tableHead',
      startTime: this.startDate ? moment(this.startDate).format('YYYY-MM-DD HH:00:00') : '',
      endTime: this.endDate ? moment(this.endDate).format('YYYY-MM-DD HH:00:00') : '',
      limit: 1
    };
    this.pmoriginService.getTableHeadData(dataObj).subscribe(
      result => this.responseUtil.success(result, this.handleHeadData),
      error => this.responseUtil.error(error)
    )
  };
  handleHeadData = (result) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      if (result.data && result.data.nameList && result.data.nameList.length > 0) {
        this.factorDataArr = result.data.nameList;
      }
      this.loadPMOri();
    } else {
      this.dialogService.info(result.message);
    }
  };
  /**
   * 导出
   */
  exportExcel = () => {
    const params = {
      siteCode: this.siteCode,
      dataType: this.timeDataType,
      startTime: this.startDate ? moment(this.startDate).format('YYYY-MM-DD HH:00:00') : '',
      endTime: this.endDate ? moment(this.endDate).format('YYYY-MM-DD HH:00:00') : '',
      limit: 100000
    };
    this.pmoriginService.getExcel(params).subscribe(
      result => this.processExport(result),
      error => this.responseUtil.error(error)
    )
  };
  processExport(result) {
    const blob = new Blob([result]);
    const reader = new FileReader();
    reader.readAsText(blob, 'utf-8');
    reader.onload = (e) => {
      if (reader.result) {
        if (reader.result.indexOf('code') !== -1) {
          const resultObj = JSON.parse(reader.result);
          if (!this.responseUtil.preSuccess(resultObj)) {
            this.dialogService.info(resultObj.message)
          }
        } else {
          let timeType = '';
          this.timeDataArr.every((val) => {
            if (val.dataType === this.timeDataType) {
              timeType = val.name;
              return false;
            } else {
              return true;
            }
          });
          const filename = '颗粒物组分分析' + '_' + (this.startDate ? moment(this.startDate).format('YYYYMMDDHH') : '')
            + '_'
            + (this.endDate ? moment(this.endDate).format('YYYYMMDDHH') : '')
            + '_'
            + timeType + '数据'
            + '_' + new Date().getTime()
            + '.xlsx';
          this.saveAs(blob, filename);
        }
      }
    }
  };
  /**
   * 保存
   * @param  {Blob} blob
   * @param  {String} filename 想要保存的文件名称
   */
  saveAs = (blob, filename) => {

    if (window.navigator.msSaveOrOpenBlob) {
      navigator.msSaveBlob(blob, filename);
    } else {
      const link = document.createElement('a');
      const body = document.querySelector('body');

      link.href = window.URL.createObjectURL(blob);
      link.download = filename;

      // fix Firefox
      link.style.display = 'none';
      body.appendChild(link);

      link.click();
      body.removeChild(link);

      window.URL.revokeObjectURL(link.href);
    }
  };
}
